package com.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;
import android.view.View;

import com.activity.adapter.CategoryAdapter;
import com.activity.adapter.CategoryListAdapter;
import com.activity.adapter.PersonAdapter;
import com.activity.bean.CategoryBean;
import com.activity.bean.OpusBean;
import com.api.param.AddWorkParam;
import com.api.param.CategoryPagePram;
import com.api.param.CategoryParam;
import com.api.param.CommentParam;
import com.api.param.UserParam;
import com.api.viewModel.StoreVM;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.donkingliang.groupedadapter.layoutmanger.GroupedGridLayoutManager;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.setting.BaseListViewActivity;
import com.example.apple.ddhr_new.activity.widget.PictureEditView;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import event.MessageEvent;

import static androidx.recyclerview.widget.StaggeredGridLayoutManager.GAP_HANDLING_NONE;

public class CategoryListActivity extends BaseListViewActivity<StoreVM> {

    private String name;
    private String id;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;

    private CategoryPagePram pageParam =new CategoryPagePram();
    private CategoryListAdapter categoryListAdapter;
    private int selectIndex;

    @Override
    protected int titleText() {
        return R.string.app_name;
    }

    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);



        name = getIntent().getExtras().getString("name");
        id = getIntent().getExtras().getString("id");
        setTitleText(name);
        pageParam.categoryid = id;

        recycleView.addItemDecoration(new PictureEditView.SquareLayoutItemDecoration(ScreenUtil.dp2px(this,0),ScreenUtil.dp2px(this,0),2));

        staggeredGridLayoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(GAP_HANDLING_NONE);
        recycleView.setItemAnimator(null);
        recycleView.setLayoutManager(staggeredGridLayoutManager);
        categoryListAdapter = new CategoryListAdapter(this);
        categoryListAdapter.id = id;
        recycleView.setAdapter(categoryListAdapter);
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                int[] first = new int[2];
//                staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(first);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
//                    staggeredGridLayoutManager.invalidateSpanAssignments();
//                }
                staggeredGridLayoutManager.invalidateSpanAssignments();
            }


            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);



            }
        });

        headerFreshing();
        listViewModel.praisePosition.observe(this,res->{
            MessageEvent messageEvent=  new MessageEvent(MessageEvent.MESSAGE_EVENT_WORK_PRAISE);
            messageEvent.worksId = categoryListAdapter.getData().get(res).getWorksid();
            messageEvent.praiseNum = listViewModel.praise.getValue();
            EventBus.getDefault().post(messageEvent);

        });
        listViewModel.workError.observe(this,error->{
            if(error){
                headerFreshEnd();
            }else {
                pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)-1)+"";
                footerFreshEnd();
            }
        });



        listViewModel.work.observe(this,data->{

            if(data.isHeader){

                categoryListAdapter.getData().clear();
                categoryListAdapter.getData().addAll(data.getResult());

                headerFreshEnd();
            }else
            {
                categoryListAdapter.getData().addAll(data.getResult());
                if(data.getResult().size()>0){
                    footerFreshEnd();
                }else
                {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }


//            if(personalAdapter.data.size()>0){
//                GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(this, 2, personalAdapter);
//                recycleView.setLayoutManager(gridLayoutManager);
//            }else {
//                recycleView.setLayoutManager(new LinearLayoutManager(this));
//            }



            showEmpty(categoryListAdapter.getData().size()==0);

            categoryListAdapter.notifyDataChanged();



        });

        categoryListAdapter.personListener = new PersonAdapter.personListener() {
            @Override
            public void praiseClick(int childPosition) {

                selectIndex =childPosition;
                CommentParam param1 = new CommentParam();
                param1.worksid = categoryListAdapter.getData().get(childPosition).getWorksid();
                addSubscription(listViewModel.addworkspraise(param1,selectIndex));
            }
        };

        listViewModel.subCategorys.observe(this,res->{

            if(res==null)
                return;
            categorys = res;
            categoryListAdapter.tag.clear();
            for (CategoryBean categoryBean : res){

                categoryListAdapter.tag.add(categoryBean.getWorkscategoryname());
            }
            categoryListAdapter.tag.add("+");
            categoryListAdapter.categorys=res;
            categoryListAdapter.notifyDataChanged();

        });

        categoryListAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {

                if(categoryListAdapter.getData().size()>0) {
                    Bundle param  = new Bundle();
                    Gson gson =new Gson();
                    param.putString("param", gson.toJson(categoryListAdapter.getData().get(childPosition)));

                    ActivityUtil.startActivity(CategoryListActivity.this,OpusDetailActivity.class,param);
                }

            }
        });

    }
    private ArrayList<CategoryBean> categorys;
    protected void headerFreshing() {
        pageParam.pagenum ="1";
        refreshLayout.resetNoMoreData();
        addSubscription(listViewModel.getCategoryWork(pageParam,true));
        CategoryParam categoryParam = new CategoryParam();
        categoryParam.categoryid = pageParam.categoryid;
        addSubscription(listViewModel.getSubCategory(categoryParam));

    }


    protected void footerFreshing() {
        pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)+1)+"";

        addSubscription(listViewModel.getCategoryWork(pageParam,false));
    }

    @Override
    public void onMessageEvent(MessageEvent event) {
        super.onMessageEvent(event);
          if(event.getMessage() == MessageEvent.MESSAGE_EVENT_DELETE_WORKS){


            boolean flag =false;
            int index=0;
            for (int i=0;i<categoryListAdapter.getData().size();i++){

                if(categoryListAdapter.getData().get(i).getWorksid().equals(event.worksId)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                categoryListAdapter .getData().remove(index);


                categoryListAdapter.notifyDataChanged();


            }


        }else  if(event.getMessage() == MessageEvent.MESSAGE_EVENT_ADD_WORKS||event.getMessage() == MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE){


              headerFreshing();

          }
        else if(event.getMessage()==MessageEvent.MESSAGE_EVENT_UPDATE_WORKS){
            boolean flag =false;
            int index=0;

            Gson gson  = new Gson();
            AddWorkParam addWorkParam = gson.fromJson(event.addwork, AddWorkParam.class);
            for (int i=0;i<categoryListAdapter.getData().size();i++){

                if(categoryListAdapter.getData().get(i).getWorksid().equals(addWorkParam.worksid)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                OpusBean data=   categoryListAdapter.getData().get(index);
                data.setWorkstitle(addWorkParam.title);
                data.setWorkscontent(addWorkParam.content);
                data.setWorkstags(addWorkParam.tags);
                data.setWorkspics(addWorkParam.pics);
                data.setWorkssizes(addWorkParam.sizes);




                categoryListAdapter.notifyDataChanged();

            }
        }
          else if(event.getMessage()==MessageEvent.MESSAGE_EVENT_WORK_PRAISE){
              boolean flag =false;
              int index=0;


              for (int i=0;i<categoryListAdapter.getData().size();i++){

                  if(categoryListAdapter.getData().get(i).getWorksid().equals(event.worksId)){
                      flag=true;
                      index =i;
                      break;
                  }
              }
              if(flag){
                  OpusBean data=   categoryListAdapter.getData().get(index);

                  data.setWorkifpraise(event.praiseNum);
                  if(event.praiseNum.equals("1")){
                      data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())+1)+"" );
                  }else {
                      data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())-1)+"" );
                  }




                  categoryListAdapter.notifyChildChanged(0,index);


              }
          }

    }
}
